#include<iostream>
#include<string>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>



std::string Usage(std::string proc)
{
    std::cout <<"Usage: "<< proc << " port" << std::endl;
}

int main(int argc,char* argv[])
{

    if(argc != 3){
        Usage(argv[0]);
        return -1;
    }

    //1.获取端口
    uint16_t port = atoi(argv[2]);

    //获取套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);

    //设置服务器端口
    struct sockaddr_in server;
    server.sin_port = htons(port);
    server.sin_family = AF_INET;

    //设置服务器ip
    server.sin_addr.s_addr =inet_addr(argv[1]);    

    char Buffer[1024];
    //使用服务器服务
    while(true)
    {
        //向服务器发送消息
        std::string s;
        std::cout<<"输入 #";
        std::cin>>s;
        sendto(sock,s.c_str(),s.size(),0,(struct sockaddr*)&server,sizeof(server));
        

        //接收服务器消息
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        //接收服务器消息
        int cnt = recvfrom(sock,Buffer,sizeof(Buffer)-1,0,(struct sockaddr*)&server,&len);
        //把服务器的消息回显
        if(cnt > 0)
        {   
            std::cout<<"server #"<<Buffer<<std::endl;
        }
        
    }

    return 0;
}